import api from "../../utils/api"; // 引入api接口管理文件

Page({
  /**
   * 页面的初始数据
   */
  data: {
    searchTxt: "",
    isShowDelete: false,
    hot: [],
    history: [],
    isShowHistoryBtn: false,
  },

  onShow() {
    this.getHotAndHistory();
  },

  /**
   * @description: 获取热搜历史数据
   */
  getHotAndHistory() {
    api.searchHotAndHistory({
      success: (res) => {
        const { code, data = {} } = res || {};
        if (+code === 0) {
          const hot = this.handleHotData(data.hotSearch || []);
          const history = this.handleHistoryData(data.searchHistory || []);
          this.setData({
            hot,
            history,
            isShowHistoryBtn: history.length > 0,
          });
        }
      },
    });
  },

  /**
   * @description: 处理热门
   * @param {*} hotSearch
   */
  handleHotData(hotSearch = []) {
    return hotSearch.map((item, index) => {
      if (item) {
        return {
          isHot: index < 3,
          txt: item,
          id: index,
        };
      }
    });
  },

  /**
   * @description: 处理历史数据
   * @param {*} searchHistory
   */
  handleHistoryData(searchHistory) {
    return searchHistory.map((item, index) => {
      if (item) {
        return {
          txt: item,
          id: index,
        };
      }
    });
  },

  /**
   * @description: 内容输入
   * @param {*} e
   * @return {*}
   */
  onBindinput(e) {
    this.setData({
      searchTxt: e.detail || "",
    });
  },

  /**
   * @description: 内容确定
   */
  onBindconfirm() {
    const { searchTxt } = this.data;
    wx.navigateTo({
      url: `../search-result/index?searchTxt=${searchTxt}`,
    });
  },

  /**
   * @description: 删除搜索历史
   */
  onDeleteHistory() {
    api.deleteHistory({
      success: (res) => {
        wx.showToast({
          title: "删除成功",
          icon: "none",
        });
        this.setData({
          history: [],
          isShowHistoryBtn: 0,
        });
      },
      fail: () => {
        wx.showToast({
          title: "删除失败, 请重试",
          icon: "none",
        });
      },
    });
  },

  /**
   * @description: 跳转搜索结果页
   * @param {*} e
   */
  goToSearch(e) {
    let searchTxt = e.currentTarget.dataset.txt || "";
    wx.navigateTo({
      url: `../search-result/index?searchTxt=${searchTxt}`,
    });
  },
});
